package top.vanchor.flexible.config.redis;

import com.aliyun.oss.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jmx.support.RegistrationPolicy;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import top.vanchor.flexible.config.consts.RedisConst;

/**
 * Created by IntelliJ IDEA.
 * 配置redis缓存
 * @Author : Ding
 * @create 2022/4/8 22:35
 */
@Slf4j
@Configuration
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class RedisConfig extends CachingConfigurerSupport {

    @Bean(name = "JedisPool")
    public JedisPool jedisPool(){
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(RedisConst.MAX_IDLE);
        jedisPoolConfig.setMinIdle(RedisConst.MIN_IDLE);
        jedisPoolConfig.setMaxTotal(RedisConst.MAX_ACTIVE);

        JedisPool jedisPool=new JedisPool(jedisPoolConfig,RedisConst.HOST,RedisConst.PORT,RedisConst.TIMEOUT, StringUtils.isNullOrEmpty(RedisConst.PASSWORD)?null:RedisConst.PASSWORD);
        log.info("JedisPool连接成功:{}:{}",RedisConst.HOST,RedisConst.PORT);

        return jedisPool;
    }

    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     *
     * @param contextFactory redis连接工厂
     * @return redisTemplate
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory contextFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        //默认的key序列化器为JdkSerializationRedisSerializer，这里改成StringRedisSerializer
        //原因是，默认的序列化器会造成 name => \xac\xed\x00\x05t\x00\x04name
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(contextFactory);
        return redisTemplate;
    }

}